package com.cube.truthseer.common.security.interceptors;

import com.cube.truthseer.common.entity.enums.ResultCode;
import com.cube.truthseer.common.exception.ServiceException;
import com.cube.truthseer.common.security.AuthUser;
import com.cube.truthseer.common.security.annotations.Login;
import com.cube.truthseer.common.security.context.UserContext;
import com.cube.truthseer.common.security.enums.UserEnums;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Aspect
@Configuration
@Slf4j
public class LoginInterceptor {

    @Autowired
    UserContext userContext;

    @Before("@annotation(loginAnnotation)")
    public void interceptor(Login loginAnnotation) {
        boolean login = loginAnnotation.value();
        //判断是否需要登录
        if (login) {
            UserEnums[] userEnums = loginAnnotation.role();
            AuthUser authUser = userContext.getLoginUser();
            if (authUser == null) throw new ServiceException(ResultCode.USER_NOT_LOGIN);
            //此时用户已经登录，现在判断接口权限是否只能是管理员
            if(userEnums.length==1&&userEnums[0]==UserEnums.MANAGER){
                if(authUser.getRole()!=UserEnums.MANAGER)
                    throw new ServiceException(ResultCode.USER_AUTHORITY_ERROR);
            }
            //判断用户身份类型
            if (Arrays.stream(userEnums).noneMatch(role -> role == authUser.getRole()))
                throw new ServiceException(ResultCode.USER_NOT_LOGIN);
        }
    }
}